import React, { useState } from 'react';
import { Card, Form, Input, Button, Upload, message, Avatar, Row, Col, Tabs, Typography } from 'antd';
import { UserOutlined, MailOutlined, PhoneOutlined, LockOutlined, UploadOutlined } from '@ant-design/icons';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import './style.less';

const { Title } = Typography;
const { TabPane } = Tabs;

interface UserInfo {
  name: string;
  email: string;
  phone: string;
  bio: string;
}

interface PasswordForm {
  currentPassword: string;
  newPassword: string;
  confirmPassword: string;
}

const Profile: React.FC = () => {
  const [userForm] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState<string>('');
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  // 模拟初始数据
  const initialUserInfo: UserInfo = {
    name: '管理员',
    email: 'admin@example.com',
    phone: '13800138000',
    bio: '系统管理员，负责系统的日常维护和管理。',
  };

  const handleUserInfoSubmit = (values: UserInfo) => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      console.log('保存用户信息:', values);
      message.success('个人信息已更新');
      setLoading(false);
    }, 1000);
  };

  const handlePasswordSubmit = (values: PasswordForm) => {
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      console.log('修改密码:', values);
      message.success('密码已修改');
      passwordForm.resetFields();
      setLoading(false);
    }, 1000);
  };

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传JPG/PNG格式的图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps['onChange'] = (info) => {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      // 模拟上传成功后获取URL
      const url = URL.createObjectURL(info.file.originFileObj as Blob);
      setAvatarUrl(url);
      message.success('头像上传成功');
    }
    setFileList(info.fileList);
  };

  const uploadButton = (
    <div>
      <UploadOutlined />
      <div style={{ marginTop: 8 }}>上传</div>
    </div>
  );

  return (
    <div className="profile-container">
      <Title level={4} className="page-title">个人信息</Title>
      
      <Card className="profile-card">
        <Tabs defaultActiveKey="info">
          <TabPane tab="基本信息" key="info">
            <Row gutter={24}>
              <Col xs={24} md={8} className="avatar-col">
                <div className="avatar-container">
                  <Avatar
                    size={120}
                    icon={<UserOutlined />}
                    src={avatarUrl}
                    className="user-avatar"
                  />
                  <Upload
                    name="avatar"
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    beforeUpload={beforeUpload}
                    onChange={handleChange}
                    maxCount={1}
                    fileList={fileList}
                  >
                    {uploadButton}
                  </Upload>
                </div>
              </Col>
              <Col xs={24} md={16}>
                <Form
                  form={userForm}
                  layout="vertical"
                  initialValues={initialUserInfo}
                  onFinish={handleUserInfoSubmit}
                >
                  <Form.Item
                    label="姓名"
                    name="name"
                    rules={[{ required: true, message: '请输入姓名' }]}
                  >
                    <Input prefix={<UserOutlined />} placeholder="姓名" />
                  </Form.Item>
                  
                  <Form.Item
                    label="邮箱"
                    name="email"
                    rules={[
                      { required: true, message: '请输入邮箱' },
                      { type: 'email', message: '请输入有效的邮箱地址' }
                    ]}
                  >
                    <Input prefix={<MailOutlined />} placeholder="邮箱" />
                  </Form.Item>
                  
                  <Form.Item
                    label="手机号"
                    name="phone"
                    rules={[
                      { required: true, message: '请输入手机号' },
                      { pattern: /^1\d{10}$/, message: '请输入有效的手机号' }
                    ]}
                  >
                    <Input prefix={<PhoneOutlined />} placeholder="手机号" />
                  </Form.Item>
                  
                  <Form.Item
                    label="个人简介"
                    name="bio"
                  >
                    <Input.TextArea rows={4} placeholder="个人简介" />
                  </Form.Item>
                  
                  <Form.Item>
                    <Button
                      type="primary"
                      htmlType="submit"
                      loading={loading}
                    >
                      保存信息
                    </Button>
                  </Form.Item>
                </Form>
              </Col>
            </Row>
          </TabPane>
          
          <TabPane tab="修改密码" key="password">
            <Form
              form={passwordForm}
              layout="vertical"
              onFinish={handlePasswordSubmit}
            >
              <Form.Item
                label="当前密码"
                name="currentPassword"
                rules={[{ required: true, message: '请输入当前密码' }]}
              >
                <Input.Password prefix={<LockOutlined />} placeholder="当前密码" />
              </Form.Item>
              
              <Form.Item
                label="新密码"
                name="newPassword"
                rules={[
                  { required: true, message: '请输入新密码' },
                  { min: 8, message: '密码长度不能少于8个字符' }
                ]}
              >
                <Input.Password prefix={<LockOutlined />} placeholder="新密码" />
              </Form.Item>
              
              <Form.Item
                label="确认新密码"
                name="confirmPassword"
                dependencies={['newPassword']}
                rules={[
                  { required: true, message: '请确认新密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('newPassword') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
              >
                <Input.Password prefix={<LockOutlined />} placeholder="确认新密码" />
              </Form.Item>
              
              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                >
                  修改密码
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </Card>
    </div>
  );
};

export default Profile;